import React, { useState, useRef, forwardRef, useImperativeHandle } from 'react';
import { Modal, Form, Input, Button } from 'antd';
import DataTypeSelect from '../form/DataTypeSelect';
import useFlowStore from '../../hooks/flowStore';

const ParamSettingModal = ({ onAdd, onEdit }, ref) => {
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const flowContext = useFlowStore();
  const originalDataRef = useRef(null);
  useImperativeHandle(ref, () => ({
    add: add,
    edit: edit
  }));

  const add = (maxId) => {
    setIsEdit(false);
    form.setFieldsValue({
      envKey: '',
      envName: '',
      dataType: null,
      envType: 3,
      id: maxId,
    });
    originalDataRef.current = form.getFieldsValue();
    setVisible(true);
  };

  const edit = (data) => {
    setIsEdit(true);
    form.setFieldsValue(data);
    originalDataRef.current = data;
    setVisible(true);
  };

  const onCancel = () => {
    setVisible(false);
  };

  const onSubmit = async () => {
    try {
      const values = await form.validateFields();

      // 校验变量编码唯一性
      if (values.envKey !== originalDataRef.current?.envKey) {
        const exists = flowContext.data.flowVariables.some(
          item => item.envKey === values.envKey
        );
        if (exists) {
          form.setFields([{
            name: 'envKey',
            errors: ['变量编码已存在'],
          }]);
          return;
        }
      }

      setVisible(false);
      if (isEdit) {
        onEdit(values);
      } else {
        onAdd(values);
      }
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  return (
    <Modal
      title={isEdit ? '编辑变量' : '新增中间变量'}
      open={visible}
      onCancel={onCancel}
      width={400}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={onSubmit}>
          确定
        </Button>,
      ]}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          envKey: '',
          envName: '',
          dataType: null,
          envType: 3,
          id: 0,
        }}
      >
        <Form.Item name={'id'} hidden />
        <Form.Item name={'envType'} hidden />
        <Form.Item
          label="变量键"
          name="envKey"
          rules={[
            { required: true, message: '请输入变量编码' },
            { pattern: /^[a-zA-Z0-9_]+$/, message: '请输入大小写字母或下划线' },
          ]}
        >
          <Input placeholder="请输入" maxLength={30} />
        </Form.Item>
        <Form.Item
          label="变量名"
          name="envName"
          rules={[{ required: true, message: '请输入变量名称' }]}
        >
          <Input placeholder="请输入" maxLength={30} />
        </Form.Item>
        <Form.Item
          label="变量类型"
          name="dataType"
          rules={[{ required: true, message: '请选择数据类型' }]}
        >
          <DataTypeSelect />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default forwardRef(ParamSettingModal); 